package com.price.exportexcel

import android.content.Context
import android.widget.Toast
import com.price.common.extend.internalCacheDirPath
import com.price.common.extend.logError
import jxl.Workbook
import jxl.WorkbookSettings
import jxl.format.Colour
import jxl.write.Label
import jxl.write.WritableCell
import jxl.write.WritableCellFormat
import jxl.write.WritableFont
import jxl.write.WritableWorkbook
import jxl.write.WriteException
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream

/**
 *         ExcelUtil.initExcel(filePath, sheetName, title);
 *         ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context);
 * */
object ExcelUtil {

    private var arial14font: WritableFont? = null
    private var arial14format: WritableCellFormat? = null
    private var arial10font: WritableFont? = null
    private var arial10format: WritableCellFormat? = null
    private var arial12font: WritableFont? = null
    private var arial12format: WritableCellFormat? = null
    private const val UTF8_ENCODING = "UTF-8"

    /**
     * 单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
     */
    private fun format() {
        try {
            arial14font = WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD)
            arial14font?.colour = Colour.LIGHT_BLUE
            arial14format = WritableCellFormat(arial14font)
            arial14format?.alignment = jxl.format.Alignment.CENTRE
            arial14format?.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN)
            arial14format?.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW)

            arial10font = WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD)
            arial10format = WritableCellFormat(arial10font)
            arial10format?.alignment = jxl.format.Alignment.CENTRE
            arial10format?.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN)
            arial10format?.setBackground(Colour.GRAY_25)

            arial12font = WritableFont(WritableFont.ARIAL, 10)
            arial12format = WritableCellFormat(arial12font);
            //对齐格式
            arial10format?.alignment = jxl.format.Alignment.CENTRE
            //设置边框
            arial12format?.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);

        } catch (e: WriteException) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Excel
     *
     * @param fileName 导出excel存放的地址（目录）
     * @param colName excel中包含的列名（可以有多个）
     */
    @JvmStatic
    fun initExcel(fileName: String,sheetName:String, colName: Array<String>) {
        format()
        var workbook: WritableWorkbook? = null
        try {
            val file = File(fileName)
            if (!file.exists()) {
                file.createNewFile()
            }
            workbook = Workbook.createWorkbook(file)
            //设置表格的名字
            val sheet = workbook.createSheet(sheetName, 0)
            //创建标题栏
            sheet.addCell(Label(0, 0, fileName, arial14format) as WritableCell)

            for ((index, col) in colName.withIndex()) {
                sheet.addCell(Label(index, 0, col, arial10format));
            }
            //设置行高
            sheet.setRowView(0, 340);
            workbook.write();
        } catch (e: Exception) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (e: Exception) {
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public fun <T> writeObjListToExcel(c: Context, objList: List<T>?, fileName: String) {
        if (!objList.isNullOrEmpty()) {
            var writebook: WritableWorkbook? = null
            var ins: InputStream? = null
            try {
                val setEncode = WorkbookSettings()
                setEncode.encoding = UTF8_ENCODING
                ins = FileInputStream(File(fileName))
                val workbook = Workbook.getWorkbook(ins)
                writebook = Workbook.createWorkbook(File(fileName), workbook)
                val sheet = writebook.getSheet(0)

                for ((j, data: T) in objList.withIndex()) {
                    val demoBean=data as DemoBean
                    val list = ArrayList<String>()
                    list.add(demoBean.Name)
                    list.add(demoBean.Age)
                    list.add(demoBean.Beizhu)

                    for ((i,label) in list.withIndex()) {
                        sheet.addCell(Label (i, j+1, label, arial12format))
                        if (label.length <= 4) {
                            //设置列宽
                            sheet.setColumnView(i, label.length+8)
                        } else {
                            //设置列宽
                            sheet.setColumnView(i, label.length+5)
                        }
                    }
                    //设置行高
                    sheet.setRowView(j+1, 350)
                }

                writebook.write()
                logError("导出Excel成功")
                Toast.makeText(c, "导出Excel成功", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                if (writebook != null) {
                    try {
                        writebook.close()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }
                if (ins != null) {
                    try {
                        ins.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }

        }
    }



    fun demo(c: Context){
        val path= "$internalCacheDirPath/demo.xlsx"//xls
        val titles= arrayOf("姓名", "年龄", "備註")
        val sheetName="DemoSheet"


        val list= mutableListOf<DemoBean>()
        list.add(DemoBean("張三","21","測試1"))
        list.add(DemoBean("李四","32","測試2"))
        list.add(DemoBean("王五","43","測試3"))
        list.add(DemoBean("趙六","54","測試4"))

        initExcel(path,sheetName,titles)
        writeObjListToExcel(c,list,path)
    }


}